package com.nidu.demo.dept.util;

import cn.hutool.core.collection.CollUtil;
import com.nidu.demo.common.constants.Constants;
import com.nidu.demo.dept.dto.DepartmentTreeCO;
import com.nidu.demo.dept.model.Department;
import com.nidu.demo.menu.model.Menu;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 部门树形结构工具类
 *
 * @author auto
 */
public class DepartmentUtil {

    /**
     * 构建部门树形结构
     *
     * @param deptList 部门列表
     * @return 树形结构列表
     */
    public static List<DepartmentTreeCO> buildDeptTree(List<DepartmentTreeCO> deptList) {
        if (CollUtil.isEmpty(deptList)) {
            return Collections.emptyList();
        }
        
        // 排序，保证部门的有序性
        deptList.sort(Comparator.comparing(DepartmentTreeCO::getSortOrder));

        // 构建部门树
        // 使用 LinkedHashMap 的原因，是为了排序
        Map<Long, DepartmentTreeCO> treeNodeMap = new LinkedHashMap<>();
        deptList.forEach(dept -> treeNodeMap.put(dept.getId(), dept));
        
        // 处理父子关系
        treeNodeMap.values().stream()
                .filter(node -> !node.getParentId().equals(Constants.ROOT_DEPT_ID))
                .forEach(childNode -> {
                    // 获得父节点
                    DepartmentTreeCO parentNode = treeNodeMap.get(childNode.getParentId());
                    if (parentNode == null) {
                        return;
                    }
                    // 将自己添加到父节点中
                    if (parentNode.getChildren() == null) {
                        parentNode.setChildren(new ArrayList<>());
                    }
                    parentNode.getChildren().add(childNode);
                });
        
        // 获得到所有的根节点
        return treeNodeMap.values().stream()
                .filter(node -> Constants.ROOT_DEPT_ID.equals(node.getParentId()))
                .collect(Collectors.toList());
    }

    /**
     * 查询所有子孙节点
     * @param deptList
     * @param parentIds
     * @return
     */
    public static List<Department> findDescendants(List<Department> deptList, Set<Long> parentIds) {
        List<Department> descendants = new ArrayList<>();
        Queue<Long> queue = new LinkedList<>(parentIds);

        Set<Long> visited = new HashSet<>();
        while (!queue.isEmpty()) {
            Long parentId = queue.poll();
            for (Department dept : deptList) {
                if (Objects.equals(dept.getParentId(), parentId) && !visited.contains(dept.getId())) {
                    descendants.add(dept);
                    queue.add(dept.getId());
                    visited.add(dept.getId());
                }
            }
        }
        return descendants;
    }

    /**
     * 构建ancestors路径
     * @param parentId 父部门ID
     * @param parent 父部门对象
     * @return ancestors路径
     */
    public static String buildAncestors(Long parentId, Department parent) {
        if (Constants.ROOT_DEPT_ID.equals(parentId)) {
            // 根部门的ancestors为"0"
            return Constants.ROOT_DEPT_ID.toString();
        }

        if (parent != null && StringUtils.hasText(parent.getAncestors())) {
            // 父部门的ancestors + 父部门ID
            return parent.getAncestors() + Constants.SEPARATOR + parentId;
        }

        // 如果父部门的ancestors为空，则只包含父部门ID
        return parentId.toString();
    }

    public static String buildAncestors(String parentId, Long id) {
        return parentId + Constants.SEPARATOR + id;
    }
} 